package com.bestcem.xm.user.controller;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.user.controller.vo.role.*;
import com.bestcem.xm.user.service.RoleService;
import com.bestcem.xm.user.service.dto.role.GetAccountRoleDTO;
import com.bestcem.xm.user.service.dto.role.RoleListDTO;
import com.bestcem.xm.user.service.dto.role.UpdateRoleDTO;
import com.bestcem.xm.user.service.dto.role.UserRoleDTO;
import com.bestcem.xm.user.util.convert.UserRoleConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Linked <zhijian.lin@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/15 16:45
 */
@RestController
@Slf4j
@RequestMapping(value = "/user/roles")
public class UserRoleController {

    @Resource
    private RoleService roleService;

    @Resource
    private UserRoleConvert userRoleConvert;

    /**
     * 根据orgId获取角色列表 通用目前不使用进行groupID，levelID筛选
     * apps_mysql/user/handlers.py:661
     *
     * @param
     * @return com.bestcem.xm.util.XmResultJson<java.util.List < com.bestcem.xm.user.controller.vo.role.RoleListVO>>
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/15 19:07
     */
    @GetMapping("/")
    public XmResultJson<List<RoleListVO>> getRoleList() {
        String orgId = SecurityContextHolder.getToken().getOrgId();
        ServiceResult<List<RoleListDTO>> result = roleService.getRoleListByOrgId(orgId);
        if (result.isSuccess()) {
            return XmResultJson.success(userRoleConvert.dtolist2Volist(result.getData()));
        }
        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }

    /**
     * 保存角色
     *
     * @param saveRoleVO
     * @return com.bestcem.xm.util.XmResultJson<java.lang.String>
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/16 14:52
     */
    @PostMapping("/")
    public XmResultJson<Map<String, String>> saveUserRole(@RequestBody SaveRoleVO saveRoleVO) {
        if (StringUtils.isBlank(saveRoleVO.getName())) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST.getCode(), "参数缺失");
        }
        UserRoleDTO userRoleDTO = userRoleConvert.saveRoleVO2DTO(saveRoleVO);
        userRoleDTO.setOrgId(SecurityContextHolder.getToken().getOrgId());
        userRoleDTO.setCreatorId(SecurityContextHolder.getToken().getUserId());
        userRoleDTO.setOperatorId(SecurityContextHolder.getToken().getUserId());

        ServiceResult<String> result = roleService.saveUserRole(userRoleDTO);
        if (result.isSuccess()) {
            Map<String, String> data = new HashMap(2);
            data.put("id", result.getData());
            return XmResultJson.success(data);
        }
        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }

    /**
     * 更新角色
     * apps_mysql/user/handlers.py:718
     *
     * @param updateSaveVO
     * @return com.bestcem.xm.util.XmResultJson<java.lang.String>
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/16 14:52
     */
    @PutMapping("/{roleId}")
    public XmResultJson<Integer> updateUserRole(@RequestBody UpdateRoleVO updateSaveVO, @PathVariable("roleId") String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST.getCode(), "参数缺失");
        }
        UpdateRoleDTO roleDTO = userRoleConvert.updateRoleVO2UpdateDTO(updateSaveVO);
        roleDTO.setRoleId(roleId);
        roleDTO.setOrgId(SecurityContextHolder.getToken().getOrgId());
        roleDTO.setOperatorId(SecurityContextHolder.getToken().getUserId());

        ServiceResult<Integer> result = roleService.updateUserRole(roleDTO);
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }
        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }


    /**
     * 删除角色
     * apps_mysql/user/handlers.py:731
     *
     * @param roleId 角色id
     * @return com.bestcem.xm.util.XmResultJson<java.lang.String>
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/16 14:52
     */
    @DeleteMapping("/{roleId}")
    public XmResultJson<Integer> deleteUserRole(@PathVariable("roleId") String roleId) {
        if (!ObjectId.isValid(roleId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "roleId为空或格式不正确");
        }
        String orgId = SecurityContextHolder.getToken().getOrgId();
        ServiceResult<Integer> result = roleService.deleteUserRole(orgId, roleId);
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }
        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }

    /**
     * 获取角色关联用户总数
     * apps_mysql/user/handlers.py:779
     * python会返回user_list(当前用户所在组及子组的用户所拥有的角色) 经前端确认该字段不需要 故不返回
     *
     * @param roleId
     * @return
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/03/16 14:31
     */
    @GetMapping("/{roleId}/users")
    public XmResultJson<UserRoleCountVO> getAccountRoleCount(@PathVariable("roleId") String roleId) {
        if (!ObjectId.isValid(roleId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_LOST, "roleId为空或格式不正确");
        }
        String orgId = SecurityContextHolder.getToken().getOrgId();
        String userId = SecurityContextHolder.getToken().getUserId();
        ServiceResult<List<GetAccountRoleDTO>> result = roleService.getAccountRoleCount(roleId, orgId, userId);
        UserRoleCountVO countVO = new UserRoleCountVO();
        List<GetAccountRoleDTO> data = result.getData();
        List<GetAccountRoleVO> userList = userRoleConvert.getAccountRoleDTO2VO(data);
        countVO.setUserList(userList);
        countVO.setTotalCount(userList.size());
        return XmResultJson.success(countVO);
    }
}

